#include "useronlinemanager.h"

UserOnlineManager::UserOnlineManager(Ui::Index *ui,QObject *parent)
    : QObject{parent}
{
    this->ui = ui;
    //图标
    QPixmap pix(":/image/res/search.jpg");
    pix.scaled(25,25);
    ui->btn_userOnline_search->setIcon(pix);
    QPixmap freshPix(":/image/res/refresh.jpg");
    ui->btn_userOnline_reset->setIcon(freshPix.scaled(25,25));
    ui->tableWidget_userOnline->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->tableWidget_userOnline->setSelectionBehavior(QAbstractItemView::SelectRows);

    init();

    // 下一页
    connect(ui->btn_userOnline_next,&QPushButton::clicked,this,[=](){
        ui->btn_userOnline_next->setEnabled(0);
        currentPage ++;
        initTable();
        initPageInfo();
    });
    //上一页
    connect(ui->btn_userOnline_pervious,&QPushButton::clicked,this,[=](){
        ui->btn_userOnline_pervious->setEnabled(0);
        currentPage --;
        initTable();
        initPageInfo();
    });
    //跳转页
    connect(ui->lineEdit_userOnline_gotoPage,&QLineEdit::returnPressed,this,[=](){
        int page = ui->lineEdit_userOnline_gotoPage->text().toInt();
        ui->lineEdit_userOnline_gotoPage->clear();
        if(page < 1 || page > totalPage){
            ui->lineEdit_userOnline_gotoPage->setStyleSheet("border:1px solid red;");
            return;
        }
        ui->lineEdit_userOnline_gotoPage->setStyleSheet("");
        currentPage = page;
        initTable();
        initPageInfo();
    });
    //    每页大小
    connect(ui->comboBox_userOnline_pageItem,SIGNAL(currentIndexChanged(int)),this,SLOT(pageSizeChanged(int)));
    //    重置
    connect(ui->btn_userOnline_reset,&QPushButton::clicked,this,[=](){
        ui->btn_userOnline_reset->setEnabled(0);
        init();
        ui->btn_userOnline_reset->setEnabled(1);
    });
    //搜索
    connect(ui->btn_userOnline_search,&QPushButton::clicked,this,[=](){
        getList();
        initTable();
        initPageInfo();
    });
}

void UserOnlineManager::pageSizeChanged(int index)
{
    switch (index) {
    case 0:
        pageSize = 5;
        break;
    case 1:
        pageSize = 10;
        break;
    case 2:
        pageSize = 20;
        break;
    case 3:
        pageSize = 50;
        break;
    case 4:
        pageSize = 100;
        break;
    default:
        break;
    }
    currentPage = 1;
    initTable();
    initPageInfo();
}

void UserOnlineManager::init()
{
    initSearchArea();
    getList();
    initTable();
    initPageInfo();
}

void UserOnlineManager::initSearchArea()
{
    ui->lineEdit_userOnline_loginLocation->clear();
    ui->lineEdit_userOnline_userName->clear();
}

void UserOnlineManager::getList()
{
    userList.clear();
    QString loginLocation = ui->lineEdit_userOnline_loginLocation->text();
    QString userName = ui->lineEdit_userOnline_userName->text();
    QByteArray *data = api.list(loginLocation,userName);
    QJsonObject obj = QJsonDocument::fromJson(*data).object();
    QJsonArray arr = obj.value("rows").toArray();
    total = obj.value("total").toInt();
    for(int i = 0;i< arr.size();i++){
        userList.append(UserOnline::toUserOnline(arr.at(i).toObject()));
    }
    if(total%pageSize == 0){
        totalPage = total / pageSize;
    }else{
        totalPage = total / pageSize + 1;
    }
    ui->label_userOnline_count->setText("共"+QString::number(total)+"条");
}

void UserOnlineManager::initTable()
{
    ui->tableWidget_userOnline->setSortingEnabled(0);
    ui->tableWidget_userOnline->sortByColumn(-1, Qt::AscendingOrder);
    ui->tableWidget_userOnline->clear();
    QStringList columnHeader;
    columnHeader << "会话编号" << "登录名称" << "部门名称" << "主机" << "登录地点" << "浏览器" << "操作系统" << "登录时间" << "操作";
    ui->tableWidget_userOnline->setColumnCount(columnHeader.size());
    ui->tableWidget_userOnline->setHorizontalHeaderLabels(columnHeader);
    ui->tableWidget_userOnline->setColumnWidth(0,270);
    ui->tableWidget_userOnline->setColumnWidth(7,150);
    int count = pageSize > userList.size() ? userList.size() : pageSize;
    int start = (currentPage-1) * pageSize;
    if(userList.size() - (currentPage-1) * pageSize < pageSize){
        count = userList.size() - (currentPage-1) * pageSize;
    }
    ui->tableWidget_userOnline->setRowCount(count);
    for(int i = 0;i< count;i++){
        ui->tableWidget_userOnline->setRowHeight(i,38);
        QString id = userList.at(start).tokenId;
        ui->tableWidget_userOnline->setItem(i,0,new QTableWidgetItem(id));
        ui->tableWidget_userOnline->setItem(i,1,new QTableWidgetItem(userList.at(start).userName));
        ui->tableWidget_userOnline->setItem(i,2,new QTableWidgetItem(userList.at(start).deptName));
        ui->tableWidget_userOnline->setItem(i,3,new QTableWidgetItem(userList.at(start).ipaddr));
        ui->tableWidget_userOnline->setItem(i,4,new QTableWidgetItem(userList.at(start).loginLocation));
        ui->tableWidget_userOnline->setItem(i,5,new QTableWidgetItem(userList.at(start).browser));
        ui->tableWidget_userOnline->setItem(i,6,new QTableWidgetItem(userList.at(start).os));
        QDateTime dateTime = QDateTime::fromMSecsSinceEpoch(userList.at(start).loginTime);
        ui->tableWidget_userOnline->setItem(i,7,new QTableWidgetItem(dateTime.toString(Qt::ISODate).replace("T"," ")));

        QWidget *tmp_widget = new QWidget();
        QHBoxLayout *tmp_layout = new QHBoxLayout();
        QPushButton *btnLogout = new QPushButton;
        connect(btnLogout,&QPushButton::clicked,this,[=](){;
            int flag  = QMessageBox::question(0,"提示","是否确认强退名称为" + userList.at(start).userName + "的用户？?",QMessageBox::Yes|QMessageBox::No);
            if(flag == QMessageBox::Yes){
                if(flag == QMessageBox::No) return;
                QByteArray *bytes = api.logout(userList.at(start).tokenId);
                QJsonObject obj = QJsonDocument::fromJson(*bytes).object();
                if(200 == obj.value("code").toInt()){
                    QMessageBox::warning(0,"提示",obj.value("msg").toString());
                    getList();
                    initTable();
                    initPageInfo();
                }
            }
        });
        btnLogout->setText("🗑强退");
        btnLogout->setFixedSize(80,35);
        btnLogout->setStyleSheet("QPushButton {padding: 5px 10px;border-style: none;border-radius: 10px;background-color: rgb(232, 244, 255);color: black;}QPushButton:hover {background-color: rgb(24, 144, 255);}QPushButton:pressed {background-color: rgb(24, 144, 200);}");
        tmp_layout->addWidget(btnLogout);
        tmp_widget->setLayout(tmp_layout);
        tmp_layout->setContentsMargins(0,0,0,0);
        ui->tableWidget_userOnline->setCellWidget(i,8,tmp_widget);
        start ++;
    }
    // 设置单元格内容居中对齐
    for (int row = 0; row < ui->tableWidget_userOnline->rowCount(); ++row) {
        for (int column = 0; column < ui->tableWidget_userOnline->columnCount(); ++column) {
            QTableWidgetItem* item = ui->tableWidget_userOnline->item(row, column);
            if (item) {
                item->setTextAlignment(Qt::AlignCenter);
            }
        }
    }
    ui->tableWidget_userOnline->setSortingEnabled(1);
}

void UserOnlineManager::initPageInfo()
{
    if(total%pageSize == 0){
        totalPage = total / pageSize;
    }else{
        totalPage = total / pageSize + 1;
    }
    ui->label_userOnline_count->setText("共"+QString::number(total)+"条");
    if(currentPage == 1){
        ui->btn_userOnline_pervious->setEnabled(0);
    }else{
        ui->btn_userOnline_pervious->setEnabled(1);
    }
    ui->label_userOnline_currentPage->setText(QString::number(currentPage));
    if(currentPage == totalPage){
        ui->btn_userOnline_next->setEnabled(0);
    }else{
        ui->btn_userOnline_next->setEnabled(1);
    }
}
